package ca.llsutherland.nfl.persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;

import ca.llsutherland.nfl.configuration.PoolConfiguration;
import ca.llsutherland.nfl.util.DeletionSpecification;
import ca.llsutherland.nfl.util.ListUtils;

import com.mysql.jdbc.Driver;

public class TestingDatabaseConnection extends AbstractDatabaseConnection {

	private static DatabaseConnectionInterface instance = new TestingDatabaseConnection();
    private static List<String> newInstances;

    public DatabaseConnectionInterface getInstance() {
        return instance ;
    }

    public void initializeConnection() throws SQLException, NamingException {
        if (getCurrentConnection() == null) {
            Driver driver = null;
            try {
                driver = (Driver)Class.forName(PoolConfiguration.getInstance().getDatabaseDriver()).newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            DriverManager.registerDriver(driver);
            String url = PoolConfiguration.getInstance().getDatabaseUrl();
            String username = PoolConfiguration.getInstance().getDbUsername();
            String password = PoolConfiguration.getInstance().getDbPassword();
            Connection connection = DriverManager.getConnection(url, username , password );
            setCurrentConnection(connection);
            initializeNewInstances();
        }
    }

    private void initializeNewInstances() {
        if(newInstances == null) {
            newInstances = new ArrayList<String>();
        }
    }

    @Override
    public void registerNewDomainObject(Long id, String tableName) {
    	newInstances.add("DELETE FROM " + tableName + " WHERE ID = " + id + ";");
    }

    @Override
    public void deleteNewDomainObjects() {
        List<String> list = ListUtils.reduce(newInstances, new DeletionSpecification());
        if(list.size() > 0) {
            newInstances = list;
            deleteNewDomainObjects();
        }
    }

    @Override
    public void removeDomainObject(Long idToRemove) {
        newInstances.remove(idToRemove);
    }

}
